import { useEffect, useState, useReducer } from 'react';
import { Button } from 'antd';
import { Table } from 'antd';

import api from '@/network/api';
import initState from '@/reducer/mock/state';
import stuReducer from '@/reducer/mock/index';
import initStulistAction, {
  updateStulistAction,
  deleteStuListAction,
} from '@/reducer/mock/action';

function EditComponent({ record, index, handleOperate }) {
  return (
    <>
      <Button
        onClick={() => handleOperate('edit', record, index)}
        type="primary"
        size="small"
      >
        编辑
      </Button>
      <Button
        onClick={() => handleOperate('delete', record, index)}
        style={{ marginLeft: '12px' }}
        type="primary"
        size="small"
        danger
      >
        删除
      </Button>
    </>
  );
}

export default function IndexPage() {
  let [state, dispatch] = useReducer(stuReducer, initState);

  const handleOperate = async (option, record, index) => {
    if (option === 'delete') {
      let editRes = await api.deleteStu({ id: record.id });
      if (editRes.code === 200) {
        dispatch(deleteStuListAction(record));
      }
    }
    console.log('获取删除结果', option, record, index);
  };
  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
    },
    {
      title: '评分',
      dataIndex: 'score',
    },
    {
      title: '创建时间',
      dataIndex: 'time',
    },
    {
      title: '操作',
      render: (_, record, index) => (
        <EditComponent
          record={record}
          index={index}
          handleOperate={handleOperate}
        />
      ),
    },
  ];
  const getStu = async () => {
    let res = await api.getStu();
    if (res.code === 200) {
      dispatch(initStulistAction(res.data));
    }
  };
  useEffect(() => {
    getStu();
  }, []);
  return (
    <div>
      {state?.stuList.length > 0 ? (
        <Table
          rowKey="objectId"
          dataSource={state?.stuList}
          columns={columns}
        />
      ) : (
        '暂无数据'
      )}
    </div>
  );
}
